package com.hejia.bulbul.scheduler;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;

import com.alibaba.fastjson.JSONObject;
import com.hejia.alauda.entity.BankCard;
import com.hejia.alauda.entity.example.BankCardExample;
import com.hejia.alauda.persistence.mybatis.BankCardMapper;
import com.hejia.alauda.utils.Pager;
import com.yeepay.yjpay.YeepayApiConfig;
import com.yeepay.yjpay.entity.BindCard;
import com.yeepay.yjpay.entity.UserBindCard;
import com.yeepay.yjpay.service.PayAPIService;

/**
 * 银行卡预留手机号同步作业
 * @author hyr
 *
 */
public class BankCardMobileSyncScheduler {

	private static final Log logger = LogFactory.getLog(BankCardMobileSyncScheduler.class);
	
	@Resource
	private BankCardMapper bankCardMapper;
	
	@Resource
	private PayAPIService payAPIService;
	
	//@Scheduled(fixedDelay = 100 * 365 * 24 * 60 * 60 * 1000)
	@Async("executor")
	public void sync() {
		
		logger.info("开始同步银行预留手机号");
		try {
			Long id = Long.MAX_VALUE;
			List<BankCard> bankCards = findBankCardsById(id);
			while(bankCards.size() > 0) {
				for(BankCard bankCard: bankCards) {
					id = bankCard.getId();
					logger.info("id:" + id);
					String bindCardListJson;
					try {
						bindCardListJson = payAPIService.bindList(
								bankCard.getUser().getExternal(), YeepayApiConfig.IDENTITY_TYPE_USER_ID);
						
						JSONObject jsonObject = JSONObject.parseObject(bindCardListJson);
						if(jsonObject.containsKey("error_code")){
							throw new RuntimeException("获取绑卡列表失败：" + bindCardListJson);
						}
						
						UserBindCard userBindCard = JSONObject.parseObject(bindCardListJson, UserBindCard.class);
						for(BindCard card : userBindCard.getCardlist()){
							// 卡号前6位和卡号后4位一致时，认为是匹配的卡
							if(bankCard.getCardNumber().startsWith(card.getCard_top())
								&& bankCard.getCardNumber().endsWith(card.getCard_last())){
								bankCard.setMobile(card.getPhone());
								bankCardMapper.updateByPrimaryKey(bankCard);
							}
						}
					} catch (Exception e) {
						logger.error("设置银行预留手机号错误", e);
					}
				}
				
				bankCards = findBankCardsById(id);
			}
		} catch (Exception e) {
			logger.info("同步银行预留手机号错误");
		}
		logger.info("结束同步银行预留手机号");
	}

	private List<BankCard> findBankCardsById(Long id) {
		Pager<BankCard> pager = new Pager<>();
		pager.setPageSize(100);
		BankCardExample example = new BankCardExample();
		example.appendCriterion("id <", id);
		example.appendCriterion("status = 'BINDED'");
		example.appendCriterion("(mobile is null or mobile = '')");
		example.setOrderByClause("id desc");
		return bankCardMapper.selectByExample(example, pager);
	}
}
